import React, { useState, useEffect } from 'react';
import {
  Table,
  Button,
  Modal,
  Form,
  Input,
  InputNumber,
  Select,
  Space,
  Card,
  Divider,
  Typography,
  message,
  Popconfirm,
  TreeSelect,
  Upload,
} from 'antd';
import {
  PlusOutlined,
  UploadOutlined,
  EditOutlined,
  DeleteOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  SyncOutlined,
  SearchOutlined,
  UndoOutlined,
  ClockCircleOutlined // 新增进度按钮图标
} from '@ant-design/icons';
import { govermentAddService, importFile, pageUsers, removeUsers, update } from '@/services/apis/serviceProviderRegister';
import area from '@/components/staticFile/region_options.json';
import { useLocation, useModel, useNavigate } from '@umijs/max';
const { Title, Text } = Typography;
const { Option } = Select;
const { TextArea } = Input;

// 状态选项
const STATUS_OPTIONS = [
  { value: '1', label: '待注册' },
  { value: '2', label: '已注册' },
];

// 获取状态标签
const getStatusTag = (status: string) => {
  switch (status) {
    case '1':
      return <Text >待注册</Text>;
    case '2':
      return <Text >已注册</Text>;
    default:
      return <Text>{status}</Text>;
  }
};

const ServiceProviderManagement: React.FC = () => {
  // 状态管理
  const [serviceProviders, setServiceProviders] = useState([]);
  const { initialState, setInitialState } = useModel('@@initialState');
  const [searchForm] = Form.useForm();
  const [currentProvider, setCurrentProvider] = useState<any>(null);
  const [visibleModal, setVisibleModal] = useState({
    addEdit: false, // 新增/编辑弹窗
    audit: false, // 审核弹窗
    progress: false, // 新增：进度弹窗
    type: '', // add/edit
  });
  const location = useLocation();
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const [pageProps, setPageProps] = useState<{ current: number, pageSize: number, total: number }>({
    current: 1,
    pageSize: 10,
    total: 0
  })

  function addSelectableToNonLeafNodes(data: any[]) {
    data.forEach((node: { children: string | any[]; selectable: boolean }) => {
      if (node.children && node.children.length > 0) {
        node.selectable = false;
        addSelectableToNonLeafNodes(node.children as any[]);
      }
    });
    return data;
  }

  useEffect(() => {
    searchUsers({ current: pageProps.current, size: pageProps.pageSize })
  }, [])

  const searchUsers = (values: any) => {
    pageUsers({
      ...values,
      loginInArea: initialState?.currentUser.data.loginInArea,
      userType: initialState?.currentUser.data.userType,
    }).then(res => {
      const { code, data } = res
      if (code == "0") {
        setServiceProviders(data.records)
        setPageProps({
          current: data.current,
          pageSize: data.size,
          total: data.total
        })
        // //message.success("请求成功")
      }
    })
  }

  const usersPageOnchange = (current: any, pageSize: any) => {
    searchUsers({ ...searchForm.getFieldsValue(), current, size: pageSize })
  }

  // 搜索处理
  const handleSearch = () => {
    searchUsers({ ...searchForm.getFieldsValue(), current: pageProps.current, size: pageProps.pageSize })
  };

  // 重置搜索
  const handleReset = () => {
    searchForm.resetFields();
    searchUsers({ current: pageProps.current, size: pageProps.pageSize })
  };

  // 打开新增弹窗
  const handleAdd = () => {
    setVisibleModal({
      addEdit: true,
      audit: false,
      progress: false,
      type: 'add',
    });
    form.resetFields();


  };

  // 打开编辑弹窗
  const handleEdit = (record: any) => {
    setCurrentProvider(record);
    setVisibleModal({
      addEdit: true,
      audit: false,
      progress: false, // 新增：关闭进度弹窗
      type: 'edit',
    });
    form.setFieldsValue(record);
  };

  // 删除服务商
  const handleDelete = (id: string) => {
    removeUsers({ id }).then(res => {
      const { code } = res;
      if (code == 0) {
        searchUsers({ ...form.getFieldsValue(), current: pageProps.current, size: pageProps.pageSize })
      }
    })
  };

  // 保存新增/编辑
  const handleSave = async () => {
    if (visibleModal.type === 'add') {
      form.validateFields().then(values => {
        govermentAddService({ ...values }).then(res => {
          const { code, msg } = res;
          if (code == "0") {
            navigate("/api_status_page", {
              state: {
                title: "服务商新加",
                message: msg,
                callbackUrl: location.pathname
              }
            });

          } else {
            navigate("/api_status_page", {
              state: {
                title: "服务商新加",
                message: msg,
                callbackUrl: location.pathname
              }
            });
          }
        })

      })
    } else {
      try {
        const values = await form.validateFields();
        update({ ...values, id: currentProvider.id, status: currentProvider.status, enterpriseCode: currentProvider.enterpriseCode }).then(res => {
          const { code } = res;
          if (code == "0") {
            // //message.success('编辑成功');

            handleSearch()
            setVisibleModal({ ...visibleModal, addEdit: false });
            navigate("/api_status_page", {
              state: {
                title: "服务商信息编辑",
                message: "服务商信息更新成功",
                callbackUrl: location.pathname
              }
            });

          }
        })
      } catch (error) {
        // 表单验证失败
        return;
      }
    }

  };

  // 导入功能（仅UI，无实际功能）
  const handleImport = async (file: any) => {

    try {
      const response = await importFile(file)
      if (response.code == "0") {
        navigate("/api_status_page", {
          state: {
            title: "服务商信息导入",
            message: response.data,
            callbackUrl: location.pathname
          }
        });
      } else {
        navigate("/api_status_page", {
          state: {
            title: "服务商信息导入",
            message: response.data,
            callbackUrl: location.pathname
          }
        });
      }
    } catch (error) {
      // handleError(error, file);
    }
  };

  // 表格列配置：新增“进度”按钮（在“审核”后）
  const columns = [
    {
      title: '序号',
      key: 'serialNumber', // 移除 dataIndex，改用 render 生成序号
      width: "10%",
      align: 'center',
      // 通过 render 函数的第二个参数 index 获取行索引（从0开始），+1 后从1开始计数
      render: (_: any, __: any, index: number) => index + 1,
    },
    {
      title: '服务商名称',
      dataIndex: 'username',
      key: 'username',
      width: "15%",
    },
    {
      title: '联系人',
      dataIndex: 'concatPerson',
      key: 'concatPerson',
      width: "15%",
    },
    {
      title: '联系电话',
      dataIndex: 'concatPhone',
      key: 'concatPhone',
      width: "15%",
    },
    {
      title: '环节',
      dataIndex: 'link',
      key: 'link',
      width: "15%",
      align: 'center',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: "15%",
      align: 'center',
      render: (status: string) => getStatusTag(status),
    },
    {
      title: '操作',
      key: 'operation',
      width: "15%",
      align: 'center',
      render: (_: any, record: any) => (
        <Space size={10}>
          <Popconfirm title="是否删除" onConfirm={() => handleDelete(record.id)}>
            <Button
              type="primary"
              size='small'
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>

          <Button disabled={record.status == "2"} type="primary"
            size='small' icon={<EditOutlined />} onClick={() => handleEdit(record)}>
            编辑
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div className="service-provider-management" style={{ padding: '20px' }}>
      <div
        style={{
          fontSize: 16,
          fontWeight: 500,
          color: '#1f2937',
          marginBottom: 12,
        }}
      >
        服务商管理
      </div>

      {/* 搜索栏 */}
      <Card style={{ marginBottom: 16 }}>
        <Form form={searchForm} layout="inline" onFinish={handleSearch}>
          <Form.Item name="productName" label="服务商名称">
            <Input allowClear placeholder="请输入服务商名称" style={{ width: 200 }} />
          </Form.Item>
          <Form.Item name="status" label="状态">
            <Select allowClear placeholder="请选择状态" style={{ width: 160 }}>
              {STATUS_OPTIONS.map((option) => (
                <Option key={option.value} value={option.value}>
                  {option.label}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
              搜索
            </Button>
          </Form.Item>
          <Form.Item>
            <Button onClick={handleReset} icon={<UndoOutlined />}>
              重置
            </Button>
          </Form.Item>
        </Form>
      </Card>

      <Card
        style={{
          borderRadius: 12,
          boxShadow: '0 2px 8px rgba(0,0,0,0.06)',
          // height: 'calc(100vh - 120px)', // 精确高度，保证内部滚动
          // overflowY: 'auto', // 内部滚动
          padding: '24px',
        }}
      >
        {/* 操作按钮行 */}
        <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'flex-start' }}>
          <Space size="middle">
            <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
              新增
            </Button>
            <Upload
              fileList={[]}
              beforeUpload={(file) => {
                // 选择文件后立即触发自动上传
                handleImport(file);
                return false; // 阻止组件默认自动上传行为，使用自定义逻辑
              }}
              // action="/upload.do"
              listType="text"
              maxCount={1}
            >
              <Button icon={<UploadOutlined />}>导入</Button>
            </Upload>
          </Space>
        </div>

        {/* 服务商列表：操作栏已新增“进度”按钮 */}
        <Table
          columns={columns as any}
          dataSource={serviceProviders}
          rowKey="id"
          className='custom-table1'
          pagination={{
            pageSize: pageProps.pageSize,
            current: pageProps.current, total: pageProps.total, showSizeChanger: true,
            onChange: usersPageOnchange
          }}
          bordered
          scroll={{ y: 'calc(100vh - 450px)', x: "hidden" }}
          locale={{ emptyText: '暂无服务商数据' }}
        />
      </Card>

      {/* 新增/编辑弹窗 */}
      <Modal
        title={visibleModal.type === 'add' ? '新增服务商' : '编辑服务商'}
        open={visibleModal.addEdit}
        onCancel={() => setVisibleModal({ ...visibleModal, addEdit: false })}
        maskClosable={false}
        width={700}
        footer={[
          <Button key="cancel" onClick={() => setVisibleModal({ ...visibleModal, addEdit: false })}>
            取消
          </Button>,
          <Button key="save" type="primary" onClick={handleSave}>
            保存
          </Button>,
        ]}
      >
        <Form form={form}>
          <Form.Item
            label="服务商名称"
            name="username"
            style={{ marginBottom: 20 }}
            rules={[{ required: true, message: '请输入服务商名称' }]}
          >
            <Input placeholder="请输入服务商名称" />
          </Form.Item>
          {/* <Form.Item
            label="登录密码"
            name="productPassword"
            style={{ marginBottom: 20 }}
            rules={[{ required: true, message: '请输入登录密码' }]}
          >
            <Input placeholder="请输入登录密码" />
          </Form.Item> */}
          <Form.Item
            label="注册地所在区(县、市)"
            name="loginInCity"
            rules={[{ required: true, message: '请选择注册城市' }]}
            style={{ marginBottom: 20 }}
            initialValue={'331100'}
          >
            <TreeSelect
              allowClear
              placeholder="请选择注册城市"
              treeData={addSelectableToNonLeafNodes(area) as any}
            />
          </Form.Item>
          <Form.Item
            label="注册地址(注明属地街道)"
            name="addr"
            style={{ marginBottom: 20 }}
            rules={[{ required: true, message: '请输入注册地址' }]}
          >
            <Input placeholder="请输入注册地址" />
          </Form.Item>
          <Form.Item
            label="企业信用代码"
            name="xydm"
            style={{ marginBottom: 20 }}
            rules={[{ required: true, message: '请输入企业信用代码' }]}
          >
            <Input placeholder="请输入企业信用代码" />
          </Form.Item>
          <Form.Item
            label="服务商类型"
            name="fwslx"
            style={{ marginBottom: 20 }}
            rules={[{ required: true, message: '请输入服务商类型' }]}
          >
            <Input placeholder="请输入服务商类型" />
          </Form.Item>
          <Form.Item
            label="联系人"
            name="concatPerson"
            rules={[{ required: true, message: '请输入联系人' }]}
            style={{ marginBottom: 20 }}
          >
            <Input allowClear placeholder="请输入联系人" />
          </Form.Item>
          <Form.Item
            label="联系方式"
            name="concatPhone"
            rules={[
              { required: true, message: '请输入联系方式' },
              {
                validator(_, value) {
                  if (!value) return Promise.resolve();
                  const v = String(value).trim().replace(/\s+/g, '');
                  return /^1[3-9]\d{9}$/.test(v)
                    ? Promise.resolve()
                    : Promise.reject(new Error('请输入有效的中国手机号'));
                },
              },
            ]}
            style={{ marginBottom: 20 }}
          >
            <Input type="tel" maxLength={11} allowClear placeholder="请输入联系方式" />
          </Form.Item>
          <Form.Item
            label="服务商简介"
            name="productExplain"
            rules={[
              { required: true, message: '请输入服务商简介' },

            ]}
            style={{ marginBottom: 20 }}
          >
            <TextArea
              placeholder="请输入服务商简介"
              showCount
              maxLength={500}
              style={{
                minHeight: 120,
                maxHeight: 300,
                resize: 'vertical',
              }}
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default ServiceProviderManagement;